package com.sl.plugin.step.selenium.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Maps;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import com.sl.core.engine.step.rowto.ProcessCompPutRowToConfig;
import com.sl.core.utils.JsonUtil;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;
import org.apache.hop.pipeline.transform.TransformMeta;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v136.network.Network;
import org.openqa.selenium.devtools.v136.network.model.Headers;
import org.openqa.selenium.devtools.v136.network.model.RequestId;
import org.openqa.selenium.devtools.v136.network.model.Response;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 *
 */
public class SeleniumInterceptorComp extends AbstractProcessComp<WebDriver, String> implements ProcessCompService {


    public SeleniumInterceptorComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }


    @SneakyThrows
    @Override
    public String input(WebDriver driver) {
        DevTools devTools = ((ChromeDriver) driver).getDevTools();
        devTools.createSession();
//        logBasic("DevTools会话已创建");
        String url = meta.getStrAttr("url");
        // 设置参数（示例值，根据需求调整）
        int maxTotalBuffer = 1024 * 1024; // 总缓冲区 1MB
        int maxResourceBuffer = 512 * 1024; // 单个资源缓冲区 512KB
        int maxPostData = 256 * 1024; // POST 数据最大 256KB

        // 启用Network域监听
        devTools.send(Network.enable(Optional.of(maxTotalBuffer), Optional.of(maxResourceBuffer), Optional.of(maxPostData)));

        logBasic("网络请求监听已启用");
        // 创建文件用于保存m3u8链接
        File tempFile = FileUtil.createTempFile();
        logBasic("输出文件已创建: " + tempFile.getAbsolutePath());
        devTools.addListener(Network.responseReceived(), response -> {

            Response res = response.getResponse();
            RequestId requestId = response.getRequestId();

            // 过滤无响应体的请求
            if (res.getStatus() == 204 || res.getStatus() == 304) {
                return; // 204(无内容)、304(未修改) 无响应体
            }
            Headers headers = res.getHeaders();
//            if ("HEAD".equals(res.getMethod())) {
//                return; // HEAD请求无响应体
//            }
            //
            String url1 = res.getUrl();
            if (url1.contains(url)) {
                // 异步获取响应内容
                CompletableFuture<Void> contentFuture = getResponseContent(devTools, res, requestId, tempFile,driver);
                contentFuture.thenRun(() -> System.out.println("响应内容处理完成"));
            }
        });
        return null;
    }

    @SneakyThrows
    private CompletableFuture<Void> getResponseContent(DevTools devTools, Response res, RequestId requestId, File tempFile, WebDriver driver) {
//        Thread.sleep(8000);
//        logBasic("===== 等待成功 =====");
        List<TransformMeta> nextTransforms = getPipelineMeta().findNextTransforms(this.getTransformMeta());

        return CompletableFuture.runAsync(() -> {
            try {
                // 获取响应内容
                Network.GetResponseBodyResponse responseBody = devTools.send(
                        Network.getResponseBody(requestId)
                );
//                logBasic("===== 获取响应成功 =====");

                // 处理响应内容（可能是JSON、HTML等）

                String rawContent = responseBody.getBody();
                logBasic("接口" + res.getUrl() + "响应内容: " + rawContent);
                // 保存链接到文件
                FileUtil.writeString(res.getUrl() + "#" + JsonUtil.toStr(rawContent), tempFile, StandardCharsets.UTF_8);
//                logBasic("链接已保存到文件");
                ProcessCompPutRowToConfig processCompPutRowToConfig = new ProcessCompPutRowToConfig();
                List<String> putToTransformNameList = Lists.newArrayList();
                List<String> collect = nextTransforms.stream().map(TransformMeta::getName).toList();
                putToTransformNameList.addAll(collect);
                processCompPutRowToConfig.setPutToTransformNameList(putToTransformNameList);
                List<Map<String, Object>> list = CollUtil.newArrayList();
                Map<String, Object> pa = Maps.newHashMap();
                pa.put("url", res.getUrl());
                pa.put("content", rawContent);
                pa.put("webDriver",driver);
                list.add(pa);
                processCompPutRowToConfig.setData(list);
                if (CollUtil.isNotEmpty(putToTransformNameList)) {
                    resultTransferRow(processCompPutRowToConfig);

                }

                // 可以在这里添加JSON解析逻辑
                // if (isJsonResponse(responseBody.getMimeType())) {
                //     parseJsonContent(content);
                // }

            } catch (Exception e) {
                e.printStackTrace();
                logError("获取响应内容失败: " + e.getMessage());
            }
        });
    }
    protected Boolean dataBreaches(){
        return Boolean.TRUE;
    }

}
